package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.TimeZoneUtil;
import util.enviaEmail;
import bean.OSBean;
import conexao.Conexao;
import dao.OSDao;

public class comentarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public comentarServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}
		
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
			String data = sdf.format(new TimeZoneUtil().getHoraLocal());
			String comentario = request.getParameter("comentario");
			Integer id = Integer.parseInt(request.getParameter("id"));
			String autor = (String) request.getSession().getAttribute("nome");
			String comentFormat = "";
			
			OSBean OS = new OSBean();
			OS.setId(id);
			
			OSBean osComent = new OSDao().getOS(conn, OS);
			
			if(osComent.getComentario() != null){
				comentFormat = osComent.getComentario() + "\n----------------------------------------------------------------------------¬\n" + autor + "         " + data + "\n" + comentario + "\n";
			}else{
				comentFormat = "\n----------------------------------------------------------------------------¬\n" + autor + "         " + data + "\n" + comentario + "\n";
			}
				
			OS.setComentario(comentFormat);
			new OSDao().alterarComentario(conn, OS);
			conn.commit();
						
			out.print(comentFormat);
			
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
				ex.printStackTrace();
			}
			new enviaEmail().enviar(e);
			throw new RuntimeException(e);
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
			}
		}		
	}
}